﻿using Microsoft.Extensions.Caching.Distributed;

namespace MyFurion.Unility.Generic
{
    /// <summary>
    /// Redis缓存
    /// </summary>
    public class RedisCacheHelper:ITransient
    {
        private readonly IDistributedCache _cache;
        public RedisCacheHelper(IDistributedCache cache)
        {
            _cache = cache;
        }
        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="time">过期时间 单位秒</param>
        public void SetRedisCache(string key, string value)
        {
            _cache.Set(key, Encoding.UTF8.GetBytes(value));
        }
        /// <summary>
        /// 设置缓存(秒)
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="time">过期时间 单位秒</param>
        public void SetRedisCache(string key,string value,int time)
        {
            _cache.Set(key, Encoding.UTF8.GetBytes(value), new DistributedCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds(time)));
        }
        /// <summary>
        /// 设置缓存(分钟)
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="time">过期时间 单位分钟</param>
        public void SetCacheMin(string key, string value, int time)
        {
            _cache.Set(key, Encoding.UTF8.GetBytes(value), new DistributedCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMinutes(time)));
        }
        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string GetReidsCache(string key)
        {
           byte[]valueByte=_cache.Get(key);
           return valueByte != null ? Encoding.Default.GetString(valueByte) : "";
        }
        /// <summary>
        /// 删除缓存
        /// </summary>
        /// <param name="key"></param>
        public void DelRedisCache(string key)
        {
            _cache.Remove(key);
        }
    }
}
